import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ModalController, LoadingController, ActionSheetController } from '@ionic/angular';
import { InstallService } from '@services/data.service/index';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';

@Component({
  selector: 'initial-step',
  templateUrl: './initial-step.html',
  styleUrls: ['initial-step.scss']
})
export class InitialComponent implements OnInit {
  @Input() roomInfo;
  @Input() installData;
  @Input() Step;
  @Output() NextNum: EventEmitter<any> = new EventEmitter();
  click = false; // 防止重复点击
  canPick = true;       // 是否可选择
  CodeInfo;
  initDatas;    // 传递给后台用户填写的值
  surveyList = {
    text: [],
    select: [],
    twotext: []
  };
  Style = {
    title: '监测数据',
    name: []
  };
  dbList = [];
  constructor(
    public modalCtrl: ModalController,
    private installService: InstallService,
    private cache: CacheService,
    private myNote: MyNoteService,
    private loadingCtrl: LoadingController,
    private actionSheetCtrl: ActionSheetController
  ) {
  }

  // 初始页面显示
  ngOnInit() {
    console.log('初始值页面房间信息', this.roomInfo);
    this.Step.state = 1;
    let txt;
    const word = [];
    txt = this.installData.data1.split(';');
    for (let i = 0; i < txt.length; i++) {
      if (txt[i]) {
        txt[i] = txt[i].split(':');
        word.push({
          name: txt[i][0],
          value: txt[i][1]
        });
      }
    }
    this.CodeInfo = word;

    // 判断是否为数据栈
    if (this.roomInfo.Type === 0) {
      this.click = true;
    } else {
      this.installService.getInitMeter(this.roomInfo.device.meterId).subscribe(res => {
        if (res.success) {
          if (res.data && res.data.initDatas.length) {
            this.click = false;
            this.initDatas = res.data.initDatas;
            this.getGroup(res.data.initDatas);
          } else {
            this.click = true;
          }
        } else {
          this.myNote.MyNotice(res.message);
        }
      });
    }
  }

  // 控件分组
  getGroup(val) {
    const value1 = [];
    const value2 = [];
    console.log('控件分组', val);
    for (let i = 0; i < val.length; i++) {
      if (val[i].controlType === 1) {
        value1.push(val[i]);

      } else if (val[i].controlType === 3) {

        const arrMark = [];
        val[i].dataValueList.forEach(item => {
          item.id = item.value;
          if (item.mark === '未安装') {
            arrMark.push(item);
          }
          // 将关联的输入类型放在一起
          for (let j = 0; j < val.length; j++) {
            if (val[j].foreginKey === val[i].key) {
              item.devices = [];
              val[j].dataValueList.forEach(ele => {
                if (ele.mark === item.mark) {
                  item.devices.push(ele);
                }
              });
            }
          }
        });
        // 默认选中可选选项第一个属性

        // console.log('可选参数', arrMark);
        // val[i].selected = arrMark[0] ? arrMark[0] : null;
        // val[i].dataList = [];
        // val[i].dataList.push(arrMark[0] ? arrMark[0] : null);
        // val[i].defaultValue = arrMark[0] ? [arrMark[0].value] : null;
        // val[i].defaultName = arrMark[0] && arrMark[0].name ? [arrMark[0].name] : null;
        value2.push(val[i]);
      }
    }
    this.surveyList.text = value1;
    this.surveyList.select = value2;
    this.dbList = value2[0].dataValueList;
    console.log(this.surveyList)

    for (const item of this.surveyList.select) {
      for (const ite of this.surveyList.select) {
        if (ite.foreginKey === item.key) {
          const array = [];
          for (const it of ite.dataValueList) {
            if (it.mark === item.dataValueList[0].mark) {
              array.push(it);
            }
          }
          ite.dataValueList = array;
        }
      }
    }
  }

  // 下拉框返回值
  selectedObj(data, e) {
    console.log(data, e)
    data.selected = null;
    data.dataList = [];
    data.dataList.push(e);
    e.key = data.key;
    for (const item of this.dbList) {
      if (item.mark === e.mark) {
        for (const val of this.surveyList.select) {
          if (val && val.foreginKey && val.foreginKey === e.key) {
            val.dataList = [];
            val.dataValueList = item.devices;
            val.selected = item.devices[0];
            val.dataList.push(item.devices[0]);
            val.defaultName = [item.devices[0].name];
            val.defaultValue = [item.devices[0].value];
          }
        }
      }
    }

    // 判断是否是联动参数值
    if (data.foreginKey) {
      for (const val of this.surveyList.select) {
        if (val && val.key && val.key === e.key) {
          val.selected = null;
          val.dataList = [];
          val.dataList.push(e);
        }
      }
    }

    data.defaultName = [e.name];
    data.defaultValue = [e.value];
  }

  // 切换步骤
  submit(i) {
    this.toNext(i);
  }

  // 判断用户信息是否填写完整
  async isFinishd() {
    let result = 0;
    console.log('提交数据', this.initDatas);
    if (this.initDatas && this.initDatas.length) {
      for (let k = 0; k < this.initDatas.length; k++) {
        if (this.initDatas[k].defaultValue && this.initDatas[k].defaultValue[0]) {
          result++;
        }
      }
      console.log(result);
      if (result === this.initDatas.length) {
        const loading = await this.loadingCtrl.create({
          spinner: 'bubbles',
          message: '正在保存信息...'
        });
        loading.present();
        this.installService.sendInitMeter(this.roomInfo.parameter.UID, this.roomInfo.device.meterId, this.initDatas).subscribe(res => {
          if (res.success) {
            loading.dismiss();
            if (res.code === 200) {
              this.click = true;
              this.canPick = false;
              this.myNote.MyNotice('保存成功');
            } else {
              this.click = false;
              this.canPick = true;
              this.myNote.MyNotice('保存失败');
            }
          } else {
            loading.dismiss();
            this.myNote.MyNotice(res.message);
          }
        });
      } else {
        this.myNote.MyNotice('请填写完整信息');
      }
    } else {
      this.click = true;
      this.canPick = false;
    }
  }

  // 确认设置
  async showTak() {
    const actionSheet = await this.actionSheetCtrl.create({
      header: '是否保存您的设置',
      cssClass: 'set-sure',
      buttons: [
        {
          text: '确认保存',
          role: 'destructive',
          handler: () => {
            this.isFinishd();
          }
        }, {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }


  toNext(i) {
    this.Step.now = i;
    this.installData.step = 5;
    this.installData.data5 = this.initDatas;
    this.installService.saveInstallData(this.installData.areaId, this.installData.meterId, this.installData);
    this.NextNum.emit(this.Step.now);
  }

}
